<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="SKU名称">
        <el-input placeholder="SKU名称" v-model="skuParams.skuName"></el-input>
      </el-form-item>
      <el-form-item label="SKU价格(元)" v-model="skuParams.price">
        <el-input placeholder="SKU价格(元)" type="number"></el-input>
      </el-form-item>
      <el-form-item label="重量(g)" v-model="skuParams.weight">
        <el-input placeholder="重量(g)" type="number"></el-input>
      </el-form-item>
      <el-form-item label="SKU描述" v-model="skuParams.skuDesc">
        <el-input placeholder="SKU描述" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="平台属性">
        <el-form :inline="true">
          <el-form-item v-for="(item, index) in attrArr" :key="item.id" :label="item.attrName">
            <el-select v-model="item.attrIdAndValueId" style="width: 100px;">
              <el-option :value="`${item.id}:${attrValue.id}`" v-for="(attrValue, index) in item.attrValueList"
                :key="attrValue.id" :label="attrValue.valueName"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-form :inline="true">
          <el-form-item v-for="(item, index) in saleArr" :key="item.id" :label="item.saleAttrName">
            <el-select style="width: 100px;" v-model="item.saleIdAndValueId">
              <el-option :value="`${item.id}:${saleAttrValue.id}`"
                v-for="(saleAttrValue, index) in item.spuSaleAttrValueList" :key="saleAttrValue.id"
                :label="saleAttrValue.saleAttrValueName"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="图片名称">
        <el-table border :data="imgArr" ref="table">
          <el-table-column type="selection" width="80px" align="center"></el-table-column>
          <el-table-column label="图片">
            <template #="{ row, $index }">
              <img :src="row.imgUrl" style="width: 100px; height: 100px;">
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"></el-table-column>
          <el-table-column label="操作">
            <template #="{ row, $index }">
              <el-button type="primary" size="small" @click="handler(row)">设置默认</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button type="primary" @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup lang='ts' name='skuForm'>
import { reqAttr } from '@/api/product/attr';
import { reqSpuImageList, reqSpuHasSaleAttr,reqAddSku } from '@/api/product/spu';
import type { SkuData } from '@/api/product/spu/type';
import { ElMessage } from 'element-plus';
import { reactive, ref } from 'vue';
//自定义事件方法
let $emit = defineEmits(['changeScene'])
//平台属性
let attrArr = ref<any>([])
//销售属性
let saleArr = ref<any>([])
//照片的数据
let imgArr = ref<any>([])
//收集SKU参数
let skuParams = reactive<SkuData>({
  //父组件传递
  category3Id: "",
  spuId: "",
  tmId: "", //品牌ID
  // v-model收集
  skuName: "",
  price: "",
  weight: "", //重量
  skuDesc: "",  //sku描述
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
  skuDefaultImg: ""  // sku图片地址
})
//获取table组件实例
let table = ref<any>()

//取消按钮回调
const cancel = () => {
  $emit('changeScene', { flag: 0, params: 'update' })
}

const initSkuData = async (c1Id: number | string, c2Id: number | string, spu: any) => {
  //收集数据
  skuParams.category3Id = spu.category3Id
  skuParams.spuId = spu.id
  skuParams.tmId = spu.tmId
  //获取平台属性
  let result: any = await reqAttr(c1Id, c2Id, spu.category3Id)
  //获取销售属性
  let result1: any = await reqSpuHasSaleAttr(spu.id)
  //获取照片墙的数据
  let result2: any = await reqSpuImageList(spu.id)
  attrArr.value = result.data
  saleArr.value = result1.data
  imgArr.value = result2.data
}
//照片设置默认按钮回调
const handler = (row: any) => {
  // 复选框只选中一个
  imgArr.value.forEach((item: any) => {
    table.value.toggleRowSelection(item, false)
  });
  //复选框选中
  table.value.toggleRowSelection(row, true)
  //收集图片地址
  skuParams.skuDefaultImg = row.imgUrl
}
//保存按钮回调
const save = async() => {
  //整理参数
  /* 
    accumulator（prev）：累积值，每次迭代都会更新。
    currentValue（next）：当前遍历的数组元素。
  */
//  平台属性
  skuParams.skuAttrValueList = attrArr.value.reduce((prev: any, next: any) => {
    if (next.attrIdAndValueId) {
      let [attrId, valueId] = next.attrIdAndValueid.split(':')
      prev.push({
        attrId,
        valueId,
      })
    }
    return prev
  }, [])
  // 销售属性
  skuParams.skuSaleAttrValueList = saleArr.value.reduce((prev: any, next: any) => {
    if (next.saleIdAndValueId) {
      let [saleAttrId,saleAttrValueId] = next.saleAttrIdAndValueName.split(':')
      prev.push({
        saleAttrId, //销售属性Id
        saleAttrValueId, //销售属性值
      })
    }
    return prev
  }, [])
  //发请求
  let result:any = await reqAddSku(skuParams)
  if(result.code == 200) {
    ElMessage({
      type:'success',
      message:'添加SKU成功'
    })
    $emit('changeScene',{flag:0,params:'update'})
  }else {
    ElMessage({
      type:'error',
      message:'添加SKU失败'
    })
  }
}

//对外保留
defineExpose({ initSkuData })
</script>


<style scoped></style>